package cn.westv.scps.web.filter;

import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.domain.SysUserEntity;
import cn.westv.scps.service.sys.config.ISysConfigService;
import cn.westv.scps.utils.PropertiesUtil;
import cn.westv.scps.utils.SpringContextUtil;
import cn.westv.scps.web.controller.base.AbstractController;

import org.apache.log4j.Logger;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.http.HttpStatus;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/08/22.
 */
public class LoginFilter implements Filter {
	private ISysConfigService sysConfigService;

	public static List<String> excludeUrl = null;

	public static String anon_url = "";

	public static String must_verify_url = "";

	private boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
		return isAjax;

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// String excludeUrlStr =
		// PropertiesUtil.getInstance().getPro("config/exludeUrl.properties",
		// "excludes");
		// String[] excludeUrls = excludeUrlStr.split("|");
		// excludeUrl = new ArrayList<String>();
		// for (String url : excludeUrls) {
		// excludeUrl.add(url);
		// }
		sysConfigService = (ISysConfigService) SpringContextUtil.getBean("sysConfigServiceImpl");
//		anon_url = sysConfigService.findByCode(ConfigCodeConstant.ANON_URL).getValue();
		must_verify_url = sysConfigService.findByCode(ConfigCodeConstant.MUST_VERIFY_URL).getValue();
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
			throw new ServletException("OncePerRequestFilter just supports HTTP requests");
		}
		HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
		HttpSession session = httpRequest.getSession(true);

		// StringBuffer url = httpRequest.getRequestURL();
		String url = httpRequest.getRequestURI();

		// ---------------------放过那些url-----------------------------
		boolean pass = false;// 默认都不可以通过
		anon_url = sysConfigService.findByCode(ConfigCodeConstant.ANON_URL).getValue();
		String[] anonUrls = anon_url.split("<br>");
		for (String urlreg : anonUrls) {
			if (url.contains(urlreg)) {
				pass = true;
				break;// 如果匹配其中一个，则表示可以通过，终止遍历
			}
		}
		if (pass) {
			filterChain.doFilter(httpRequest, httpResponse);// 如果符合，放行。且不需要继续处理下边的过滤
			return;
		}
		// ---------------------放过那些url-----------------------------
		// 如果不包含以上的url，则需要通过下边的筛选
		// ------------拦截这些---------------------
		pass = true;// 先默认都可以通过
		String[] mustVerifyUrls = must_verify_url.split("<br>");
		for (String mUrl : mustVerifyUrls) {
			if (url.contains(mUrl)) {
				pass = false;// 只要匹配任何其中一个，则不允许通过，终止遍历
				break;
			}
		}
		if (pass) {
			filterChain.doFilter(httpRequest, httpResponse);// 如果符合，放行
			return;
		}
		// ------------拦截这些---------------------

		// 正则表达式判断排除的url
		// for (String urlReg : excludeUrl) {
		// Pattern pattern = Pattern.compile(urlReg);
		// Matcher matcher = pattern.matcher(url);
		// if (matcher.matches()) {
		// filterChain.doFilter(servletRequest, servletResponse);
		// return;
		// }
		// }
		Object object = session.getAttribute(AbstractController.SESSION_USER_INFO);
		SysUserEntity user = object == null ? null : (SysUserEntity) object;
		if (user == null) {
			boolean isAjaxRequest = isAjaxRequest(httpRequest);
			if (isAjaxRequest) {
				httpResponse.setCharacterEncoding("UTF-8");
				httpResponse.sendError(HttpStatus.UNAUTHORIZED.value(), "您已经太长时间没有操作,请刷新页面");
			}
			Logger logger = Logger.getLogger(LoginFilter.class);
			logger.debug(httpRequest.getContextPath() + "/login.jsp");
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
			return;
		}
		filterChain.doFilter(servletRequest, servletResponse);
		return;
	}

	@Override
	public void destroy() {

	}
}
